# 作者：陈睿-cruise
# 2025年02月11日11时28分47秒
# 2979386061@qq.com
from Student import Student
class StudentManager():
    def __init__(self):
        self.students=[]

    @staticmethod
    def menu():
        print('-' * 40)
        print('欢迎使用学生管理系统')
        print('【1】添加学生信息')
        print('【2】删除学生信息')
        print('【3】修改学生信息')
        print('【4】查询学生信息')
        print('【5】遍历学生信息')
        print('【6】保存学生信息')
        print('【0】退出系统')
        print('-' * 40)

    def add_student(self):
        name = input('请输入学生的姓名')
        age = input('请输入学生的年龄')
        mobile = input('请输入学生的电话')
        stu=Student(name,age,mobile)
        self.students.append(stu)
        print('添加成功')

    def find_student(self):
        name = input('请输入要查找的姓名')
        for i in self.students:
            if i.name == name:
                print(i)
                break
            else:
                print('查无此人')
    def del_student(self):
        name = input('请输入要删除的姓名')
        for i in self.students:
            if i.name == name:
                self.students.remove(i)
                print('成功删除')
                break
            else:
                print('查无此人')

    def edit_student(self):
        name = input('请输入要修改的姓名')
        for i in self.students:
            if i.name == name:
                i.name = input('请输入修改后的学生姓名')
                i.age = input('请输入修改后的学生年龄')
                i.mobile = input('请输入修改后的学生电话')
                print('成功修改')
                break
            else:
                print('查无此人')

    def show_student(self):
        for i in self.students:
            print(i)

    def save_data_to_file(self):
        f = open('student.txt','w',encoding='utf-8')
        #列表推导式
        self.students=[i.__dict__ for i in self.students]
        f.write(str(self.students))
        f.close()
        print('数据保存完毕')

    def load_data_to_list(self):
        try:
            f=open('student.txt','r',encoding='utf-8')
        except Exception as e:
            f=open('student.txt','w',encoding='utf-8')
        else:
            content=f.read()
            if not content:
                self.students=[]
            self.students=eval(content)
            self.students=[Student(i['name'],i['age'],i['mobile']) for i in self.students]

    def run(self):
        self.load_data_to_list()
        while True:
            self.menu()
            user_num=int(input('请输入要执行的功能编号'))
            if user_num == 1:
                self.add_student()
            elif user_num == 2:
                self.del_student()
            elif user_num == 3:
                self.edit_student()
            elif user_num == 4:
                self.find_student()
            elif user_num == 5:
                self.show_student()
            elif user_num == 6:
                self.save_data_to_file()
            elif user_num == 0:
                print('退出系统成功，感谢使用')
                break